/*
 * 作者		www.TheWk.cn.vc
 * 开发环境	Windows7 64位 MyEclipse8.6 JDK1.6.0_45
 * 开发日期	2014年6月12日
 */
package common.log;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * <hr/>
 * 
 * @author www.TheWk.cn.vc
 * @version 1.0 2014年6月12日
 * @class common.log.MgrExceptionLogger
 */
@Aspect
public class MgrExceptionLogger {

	private Logger              logger     = LoggerFactory.getLogger(this.getClass());

	/**
	 * 记录mgr层异常的日志
	 */
	@AfterThrowing(throwing = "ex", value = "execution(public * com.dicunicom.upl.mgr.impl.*MgrImpl.*(..))")
	public void doRecordExceptionLog(JoinPoint jp, Throwable ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("IpAddr:[" + this.getClientIpAddr() + "]");
			Object[] args = jp.getArgs();
			if (args != null && args.length > 0) {
				for (int i = 0; i < args.length; i++) {
					if(args[i]!=null)
						logger.warn("第" + i + "个参数:[" + args[i].getClass().getSimpleName() + "],[" + args[i].toString() + "]");
					else
						logger.warn("第" + i + "个参数:[null]");
				}
			}
			logger.warn("出错方法:[" + jp.getTarget().getClass().getName() + "." + jp.getSignature().getName() + "]", ex);
		}
	}

	/**
	 * 获取连接的IP地址
	 */
	private String getClientIpAddr() {
		HttpServletRequest request = null;
		try{
			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		}catch(Exception e){
			return "";
		}
		final String UNKNOWN = "unknown";
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");
		if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();
		return ip;
	}

}
